﻿using System.Collections.Generic;
using System.Configuration;

namespace XTemplate.Utils
{
    internal class AppsettingsHelper
    {
        #region 本机

        public static bool SetConfigValue(string key, string value)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                if (config.AppSettings.Settings[key] != null)
                    config.AppSettings.Settings[key].Value = value;
                else
                    config.AppSettings.Settings.Add(key, value);
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static string GetConfigValue(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }

        #endregion 本机

        public List<Configuration> GetConfigurationList(List<string> files)
        {
            var list = new List<Configuration>();
            foreach (var item in files)
            {
                if (System.IO.File.Exists(item))
                    list.Add(GetConfiguration(item));
            }
            return list;
        }

        public Configuration GetConfiguration(string cfgName)
        {
            var mapping = new ExeConfigurationFileMap()
            {
                ExeConfigFilename = cfgName
            };
            var config = ConfigurationManager.OpenMappedExeConfiguration(mapping, ConfigurationUserLevel.None);
            return config;
        }

        public ConnectionStringSettingsCollection GetConnectionStringSettingsCollection(Configuration cfg)
        {
            return cfg.ConnectionStrings.ConnectionStrings;
        }

        public ConnectionStringSettings ModifyConnectionStr(ConnectionStringSettings conn, string key = "", string value = "")
        {
            if (!string.IsNullOrEmpty(key.Trim()))
                conn.Name = key.Trim();
            if (!string.IsNullOrEmpty(value.Trim()))
                conn.ConnectionString = value.Trim();
            return conn;
        }
    }
}